package com.sky.service.impl;

import com.sky.dto.DishDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DishServiceImpl implements DishService {
    //静态资源配置
    @Autowired
    private DishMapper dishMappere;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    /**
     * 新增菜品及对应的接口
     * @param dishDTO
     */
    @Override
    public void saveWithFlavor(DishDTO dishDTO) {
        //补全对象数据
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        //向菜品中插入数据
        dishMappere.insert(dish);

        //获得insert语句生成的主键值  有mapper中的一个注解完成这个功能
        Long dishId = dish.getId();

        //给口味对象添加外键 dishId
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(flavors!=null && flavors.size()>0) {
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishId);
            });
            //向口味表中添加n条数据
            dishFlavorMapper.insertBatch(flavors);
        }
    }
}
